import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'

const service = axios.create({
  // baseURL: 'http://ihrm-java.itheima.net',
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
}) // 创建一个axios的实例

// import { getToken } from '@/utils/auth'

// 添加请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  })

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.success) {
      return response.data
    } else {
      return Promise.reject(new Error(response.data.message))
    }
  },
  async error => {
    if (error.response.status === 401) {
      await store.dispatch('user/logout')
      console.log(router)
      router.push(`/login?redirect=${router.history.pending.fullPath}`)
    }
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service // 导出axios实例
